package com.tom.joke;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import java.util.List;

/**
 * Added by Tom on 2024/07/03.
 * 5.0+ 才可使用 JobService
 * <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 * 添加权限：android:permission="android.permission.BIND_JOB_SERVICE"
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobWakeUpService extends JobService {
    private final int JOB_WAKE_UP_ID = 1;


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("TAG","onStartCommand");
        // 开启轮询，
        JobInfo.Builder jobBuilder = new JobInfo.Builder(JOB_WAKE_UP_ID,
                new ComponentName(this, JobWakeUpService.class));
        jobBuilder.setPeriodic(2 * 1000); // 轮询时间设置

        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(jobBuilder.build());
        return START_STICKY;
    }

    @Override
    public boolean onStartJob(JobParameters params) { // 轮询回调
        Log.e("TAG","onStartJob");
        // 开启定时任务，定时轮询。看MessageService 有没有被杀死，
        // 如果杀死了，就启动这个Service。轮询onStartJob
        boolean isMsgServiceAlive = isServiceWork(this, MessageService.class.getName());
        if(!isMsgServiceAlive) { // 只需要启动一个即可。守护进程这边不需要启动。
            startService(new Intent(this, MessageService.class));
        }
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return false;
    }

    /**
     * 判断某个服务是否正在运行的方法，服务是否被杀死了。
     *
     * @param mContext
     * @param serviceName
     *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(Context mContext, String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(100);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName().toString();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
}
